package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.domain.ClientInfo;
import com.ruoyi.system.service.PushMessageService;
import com.ruoyi.system.util.RedisKeys;
import com.ruoyi.system.util.TypeReferences;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class PushMessageServiceImpl implements PushMessageService {

	@Value("${unipush.apps.app-id}")
	private String appId;
	@Autowired
	private RedisService redisService;

	/**
	 * 更新用户clientid
	 * @param clientInfo
	 * @param userId
	 */
	@Override
	public void updateClientid(ClientInfo clientInfo, Long userId) {

		if(null != clientInfo.getTarget() && null != clientInfo.getUserLogin() && clientInfo.getUserLogin().length() > 0){
			Map<String, ClientInfo> userClientInfo;
			if (redisService.hasKey(RedisKeys.CLIENTID)) {
				userClientInfo = JSON.parseObject(redisService.getCacheObject(RedisKeys.CLIENTID).toString(), TypeReferences.clientidTypeReference);
			} else {
				userClientInfo = new HashMap<>();
			}
			clientInfo.getTarget().setAppId(appId);
			userClientInfo.put(userId.toString(), clientInfo);
			redisService.setCacheObject(RedisKeys.CLIENTID, JSON.toJSONString(userClientInfo));
		}else {
			log.info("==============================================更新错误：{}",JSON.toJSONString(clientInfo));
		}
		log.error("==============================================updateClientid:{}", JSON.toJSONString(redisService.getCacheObject(RedisKeys.CLIENTID)));
	}


}
